import React, { useState, useEffect } from 'react';
import { Card, Space, DatePicker, Select, message } from 'antd';
import DataTable from '../../../components/common/DataTable';
import { getAttendanceHistory } from '../../../api/attendance';

const { RangePicker } = DatePicker;
const { Option } = Select;

const AttendanceManagement = () => {
    const [loading, setLoading] = useState(false);
    const [dataSource, setDataSource] = useState([]);
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0
    });
    const [filterDate, setFilterDate] = useState([]);
    const [filterStatus, setFilterStatus] = useState(null);

    useEffect(() => {
        fetchAttendances();
    }, [pagination.current, pagination.pageSize, filterDate, filterStatus]);

    // 获取考勤记录
    const fetchAttendances = async () => {
        setLoading(true);
        try {
            const params = {
                page: pagination.current,
                pageSize: pagination.pageSize,
                status: filterStatus
            };
            
            if (filterDate && filterDate.length === 2) {
                params.startDate = filterDate[0].format('YYYY-MM-DD');
                params.endDate = filterDate[1].format('YYYY-MM-DD');
            }
            
            const response = await getAttendanceHistory(params);
            
            setDataSource(response.data || []);
            setPagination({
                ...pagination,
                total: response.total || 0
            });
        } catch (error) {
            console.error('获取考勤记录失败:', error);
            message.error('获取考勤记录失败');
        } finally {
            setLoading(false);
        }
    };

    // 处理表格变化
    const handleTableChange = (pagination) => {
        setPagination(pagination);
    };

    // 处理搜索
    const handleSearch = (value) => {
        setPagination({ ...pagination, current: 1 });
        // 实际项目中这里可以添加搜索逻辑
        console.log('搜索:', value);
    };

    // 处理日期范围变化
    const handleDateRangeChange = (dates) => {
        setFilterDate(dates);
        setPagination({ ...pagination, current: 1 });
    };

    // 处理状态筛选变化
    const handleStatusChange = (value) => {
        setFilterStatus(value);
        setPagination({ ...pagination, current: 1 });
    };

    // 获取状态标签样式
    const getStatusTag = (status) => {
        switch (status) {
            case 0:
                return { color: 'default', text: '未签到' };
            case 1:
                return { color: 'processing', text: '已签到' };
            case 2:
                return { color: 'success', text: '已签退' };
            case 3:
                return { color: 'warning', text: '迟到' };
            case 4:
                return { color: 'warning', text: '早退' };
            case 5:
                return { color: 'error', text: '缺勤' };
            default:
                return { color: 'default', text: '未知' };
        }
    };

    // 获取请假类型文本
    const getLeaveTypeText = (type) => {
        switch (type) {
            case 1:
                return '事假';
            case 2:
                return '病假';
            case 3:
                return '年假';
            case 4:
                return '调休';
            default:
                return '无';
        }
    };

    // 表格列定义
    const columns = [
        {
            title: '员工姓名',
            dataIndex: 'employeeName',
            key: 'employeeName'
        },
        {
            title: '日期',
            dataIndex: 'date',
            key: 'date',
            sorter: (a, b) => new Date(a.date) - new Date(b.date)
        },
        {
            title: '签到时间',
            dataIndex: 'checkIn',
            key: 'checkIn',
            render: (text) => text || '-'
        },
        {
            title: '签退时间',
            dataIndex: 'checkOut',
            key: 'checkOut',
            render: (text) => text || '-'
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (status) => {
                const { color, text } = getStatusTag(status);
                return <Tag color={color}>{text}</Tag>;
            }
        },
        {
            title: '请假类型',
            dataIndex: 'leaveType',
            key: 'leaveType',
            render: (type) => getLeaveTypeText(type)
        },
        {
            title: '请假时长',
            dataIndex: 'leaveTime',
            key: 'leaveTime',
            render: (time) => time > 0 ? `${time}小时` : '-'
        },
        {
            title: '位置',
            dataIndex: 'location',
            key: 'location',
            ellipsis: true
        },
        {
            title: '备注',
            dataIndex: 'remark',
            key: 'remark',
            ellipsis: true
        }
    ];

    return (
        <Card title="考勤记录管理" bordered={false} extra={
            <Space>
                <RangePicker onChange={handleDateRangeChange} />
                <Select 
                    placeholder="选择状态" 
                    style={{ width: 120 }} 
                    allowClear
                    onChange={handleStatusChange}
                >
                    <Option value={0}>未签到</Option>
                    <Option value={1}>已签到</Option>
                    <Option value={2}>已签退</Option>
                    <Option value={3}>迟到</Option>
                    <Option value={4}>早退</Option>
                    <Option value={5}>缺勤</Option>
                </Select>
            </Space>
        }>
            <DataTable 
                columns={columns}
                dataSource={dataSource}
                loading={loading}
                pagination={pagination}
                onChange={handleTableChange}
                onSearch={handleSearch}
                searchPlaceholder="搜索考勤记录"
                rowKey="id"
            />
        </Card>
    );
};

export default AttendanceManagement;